import 'package:flutter/material.dart';

class FocusTestRoute extends StatefulWidget {
  const FocusTestRoute({super.key});

  @override
  State<StatefulWidget> createState() => _FocusTestRouteState();

}

class _FocusTestRouteState extends State<FocusTestRoute> {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home:_Home()
    );
  }

}

class _Home extends StatelessWidget {

  FocusNode focusNode1 = FocusNode();
  FocusNode focusNode2 = FocusNode();
  late FocusScopeNode scopeNode;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("控制焦点"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          children: <Widget>[
            TextField(
              autofocus: true,
              focusNode: focusNode1,
              decoration: const InputDecoration(
                  labelText: "input1",
                  //未选中时下划线颜色
                  enabledBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.blue)
                  ),
                  //获得焦点时下划线颜色
                  focusedBorder: UnderlineInputBorder(
                      borderSide: BorderSide(color: Colors.red)
                  )
              ),
            ),
            TextField(
              focusNode: focusNode2,
              decoration: const InputDecoration(
                  labelText: "input2",
              ),
            ),
            Builder(builder: (context) {
              return Column(
                children: <Widget>[
                  ElevatedButton(onPressed: (){
                    //第一种移动焦点的方法
                    scopeNode;
                    scopeNode.requestFocus(focusNode2);
                    //第二种移动焦点的方法
                    // FocusScope.of(context).requestFocus(focusNode2);
                  },
                    child: Text("移动焦点"),
                  ),
                  ElevatedButton(onPressed: () {
                    // 当所有编辑框都失去焦点时键盘就会收起
                    focusNode1.unfocus();
                    focusNode2.unfocus();
                  },
                    child: Text("隐藏键盘"),
                  ),
                ],
              );
            })
          ],
        ),
      ),
    );
  }

}